package com.chenzp.rocketmq.simple;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @Classname AsyncProducer
 * @Description
 * @Version 1.0.0
 * @Date 2025-06-12 16:28
 * @Created by ncs
 */
@Slf4j
public class AsyncProducer {

    @SneakyThrows
    public static void main(String[] args) {
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer("my-group-producer");
        defaultMQProducer.setNamesrvAddr("192.168.125.102:9876");
        defaultMQProducer.start();
        int messageCount = 100;
        CountDownLatch countDownLatch = new CountDownLatch(messageCount);
        for (int i = 0; i < messageCount; i++) {
            Message message = new Message("myTopic1", "TagA", ("第" + i + "条消息").getBytes(StandardCharsets.UTF_8));
            defaultMQProducer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    countDownLatch.countDown();
                    log.info("{}异步消息发送成功{}",message, sendResult);
                }

                @Override
                public void onException(Throwable e) {
                    countDownLatch.countDown();
                    log.error("{}异步消息发送失败",message, e);
                }
            });
        }
        log.info("主线程继续执行");
        //最多等待五秒 五秒以后计数变成0
        boolean await = countDownLatch.await(5, TimeUnit.SECONDS);
        log.info(await ? "success" : "fail");
        defaultMQProducer.shutdown();
    }
}
